import json
import time

import jwt
from django.contrib.auth import authenticate
from django.http import JsonResponse

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View

from houseManage import settings
from user import authorization
from user.models import UserProfile


def register(request):
    # 得到的数据转换为字典
    json_data = request.body.decode()
    data = json.loads(json_data)
    username = data['username']
    email = data['email']
    password_1 = data['password_1']
    password_2 = data['password_2']
    # phone = data['phone']
    # sms_num = data['sms_num']
    # 做验证
    # 参数基本检查
    if password_1 != password_2:
        result = {'code': 10100, 'error': 'The password is not same~'}
        return JsonResponse(result)

    # 检查用户名是否可用
    old_users = UserProfile.objects.filter(username=username)
    if old_users:
        result = {'code': 10101, 'error': 'The username is already existed'}
        return JsonResponse(result)

    # 插入数据库
    UserProfile.objects.create_user(username=username, nickname=username, password=password_1, email=email,
                                    )

    result = {'code': 200, 'username': username, 'data': {}}
    return JsonResponse(result)

def login(request):
    # 接收用户名密码
    data = json.loads(request.body)
    username = data.get('username')
    password = data.get('password')
    print(username,password)
    # 验证用户名密码
    if authenticate(username=username, password=password):
        return JsonResponse({'code': 200, 'username': username, 'data': {'token': make_token(username)}})

    return JsonResponse({'code': 10101, 'error': '用户名或密码错误'})

class UserView(View):
    # /v1/users/tarena
    def get(self, request, username):
        try:
            user = UserProfile.objects.get(username=username)
        except Exception as e:
            result = {'code': 10102, "error": "没有该用户"}
        else:
            result = {"code": 200, "username": username,
                      'data': {'info': user.info, 'sign': user.sign, 'nickname': user.nickname,
                               "avatar": str(user.avatar)}}
        return JsonResponse(result)

    @method_decorator(authorization)
    def put(self, request, username):
        data = json.loads(request.body)

        user = request.user
        user.sign = data.get("sign")
        user.info = data.get("info")
        user.nickname = data.get("nickname")
        user.save()
        return JsonResponse({'code': 200})

# # 头像
# def avatar(request):
#     token = request.META.get('HTTP_AUTHORIZATION')
#     if not token:
#         return JsonResponse({"code": 200, "data": {"is_logged_in": 0, "avatar": ""}})
#
#     try:
#         res = jwt.decode(token, settings.KEY, algorithms='HS256')
#     except:
#         return JsonResponse({"code": 200, "data": {"is_logged_in": 0, "avatar": ""}})
#
#     username = res['username']
#     user = UserProfile.objects.get(username=username)
#
#     return JsonResponse({"code": 200, "data": {"is_logged_in": 1, "username": username, "avatar": str(user.avatar)}})

# 更改头像
@authorization
def change_avatar(request, username):
    user = request.user
    # 获取所有文件
    avatar = request.FILES['avatar']
    user.avatar = avatar
    user.save()
    return JsonResponse({'code': 200})

@authorization
def change_password(request, username):
    data = json.loads(request.body)

    old_pass = data.get("old_password")
    passwd1 = data.get("password_1")
    passwd2 = data.get("password_2")

    if passwd1 != passwd2:
        return JsonResponse({'code': 10103, 'error': "两次密码不一致"})

    if authenticate(username=username, password=old_pass):
        request.user.set_password(passwd1)
        request.user.save()
        return JsonResponse({'code': 200, 'username': username})
    else:
        return JsonResponse({'code': 10104, 'error': "原密码错误"})





# ===================工具===================
def make_token(username):
    key = settings.KEY
    payload = {'username': username, 'exp': time.time() + 86400}
    return jwt.encode(payload, key, algorithm='HS256')
